package org.yaukie.websocket.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * websocket 拦截器
 * @author yaukie
 *
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor  {
	
	private static final Logger log = Logger.getLogger(HandshakeInterceptor.class);
	
	/**
	 * 初次握手访问
	 */
	@Override
	public boolean beforeHandshake(ServerHttpRequest req, ServerHttpResponse rep,
			WebSocketHandler handler, Map<String, Object> map) throws Exception {
			log.debug("HandshakeInterceptor beforeHandshake starts ");
			if(req instanceof ServletServerHttpRequest){
				HttpServletRequest request = ((ServletServerHttpRequest) req).getServletRequest();
				HttpSession  session = request.getSession(false);
				if(session != null ){
					String userName =request.getSession().getAttribute("SESSION_USERNAME")+"";
					map.put("BROADCUST_USERNAME", userName);
				}
			
			}
		
			return true;
	} 
	
	/**
	 * 初次握手访问之后
	 */
	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse rep,
			WebSocketHandler handler, Exception excep) {
		
	}
	

}
